#!/usr/bin/env python2

from itertools import groupby
import rospy
from std_msgs.msg import Empty, String

if __name__ == '__main__':
    rospy.init_node('toolbar_event_publisher')

    spec_param = rospy.get_param('toolbarSpecifications')
    specs = [list(group) for k, group in groupby(spec_param, lambda x: x == 'spec') if not k]

    publishers = {}

    for spec in specs:
        bar = spec[0]
        buttons = spec[1:]
        for b in buttons:
            if ',' in b:
                buttons.remove(b)
                buttons.extend(b.split(','))
        for button in buttons:
            for mode in 'pressed', 'released':
                button_event = '_'.join((bar, button, mode))
                button_topic = '/'.join((bar, button, mode))
                publishers[button_event] = rospy.Publisher('state/'+button_topic, Empty, queue_size=10)

    def handler(msg):
        publishers[msg.data].publish(Empty())

    subscriber = rospy.Subscriber('state/buttonEvent', String, handler, queue_size=10)

    rospy.spin()